<?php

namespace common\behavior\CommonMessagePushing;


use common\model\ReviewRequestModel;
use common\model\ReviewRequestNodeModel;
use common\model\TaskModel;
use common\model\VersionModel;
use common\service\TaskService;
use Webman\Stomp\Client;

/**
 * 任务审核结果行为 消息通知
 */
class TaskReviewResultV2Behavior
{
    /**
     * 审核未通过 通知之前通过的所有人和提交人
     * 审核通过 通知提交人
     * 外部任务审核 查询关联的外部任务 以及外部任务审核关系
     * @param $params
     * @return void
     */
    public function run($params)
    {
        if (($params['type'] ?? 'default') !== 'result') {
            return;
        }
        $params = $params['data'];
        $version = model(VersionModel::class)->find($params['version_id']);
        if (empty($version) || module_by_id($version['module_id'])['code'] !== 'task') {
            return;
        }
        $task = model(TaskModel::class)->find($version['link_id']);
        $reviewRequest = model(ReviewRequestModel::class)->find($params['review_request_id']);
        if (empty($task) || empty($reviewRequest)) {
            return;
        }
        $taskService = TaskService::getInstance();
        $parentTask = $taskService->getParentTask($task['id'], $task['project_id']);
        $tenantId = $params['tenant_id'];

        $nodes = model(ReviewRequestNodeModel::class)
            ->where([
                'review_request_id' => $reviewRequest['id'],
                'is_reviewed' => "yes",
            ])
            ->order("id ASC")
            ->select();
        $lastReviewerNode = $nodes[count($nodes) - 1];


//        $lastReviewer = $usersMap[$lastReviewerNode['plan_reviewer']] ?? ['name' => 'None'];
//            'review_at' => date("Y/m/d H:i", $lastReviewerNode['reviewed']),

        $receiver = $params['receiver'] ?? [];
        if (empty($receiver)) {
            if ($parentTask && $parentTask['type'] == "shadow" && $tenantId != $parentTask['tenant_id']) {
                //当前审核 甲方审核  审核的是外部任务
                //查询外部审核请求数据 通知审核人
                $reviewRequestParam = json_decode($reviewRequest['param'], true);
                $partyBReviewRequestId = $reviewRequestParam['parent_review_request_id'] ?? 0;
                if ($partyBReviewRequestId) {
                    // 通知乙方审核流的审核人
                    $partyBReviewRequestNodes = model(ReviewRequestNodeModel::class)
                        ->where([
                            'review_request_id' => $partyBReviewRequestId,
                            'is_reviewed' => "yes",
                            'plan_reviewer' => ['GT', 0],
                        ])
                        ->order("id ASC")
                        ->select();
                    $partyBUsers = array_column($partyBReviewRequestNodes, 'plan_reviewer', 'plan_reviewer');
                    $receiver = array_map(fn($userId) => [
                        'user_id' => $userId,
                        'role' => 'plan_reviewer_party_b',
                    ], $partyBUsers);
                }
                // 审核不通过 通知甲方审核人
                if (!$params['is_pass']) {
//                $tenant = teamones_request('teamones-im', 'tenant/find', ['param' => ['filter' => ['id' => $parentTask['tenant_id']]]])['data'];
                    foreach ($nodes as $node) {
                        if ($node['id'] == $lastReviewerNode['id']) {
                            continue;
                        }
                        $receiver[] = [
                            'user_id' => $task['executor'],
                            'role' => 'executor',
                        ];
                    }
                }
            } else {
                // 审核内部任务
                if (!$params['is_pass']) {
                    $reviewerIdArray = array_column($nodes, 'plan_reviewer', 'plan_reviewer');
                    $receiver = array_map(fn($userId) => [
                        'user_id' => $userId,
                        'role' => 'plan_reviewer',
                    ], $reviewerIdArray);
                }
                $receiver[] = [
                    'user_id' => $task['executor'],
                    'role' => 'executor',
                ];
            }
        }

        // 组装消息包
        $data = [
            'source_user_id' => $params['user_id'] ?? \request()->getUserId(),
            'review_pass' => $params['is_pass'] ? 'yes' : 'no',
            'time' => $params['time'] ?? time(),
            'source_id' => $task['id'],
            'source_module_code' => 'task',
            'category' => 'task_review_finish',
            'receiver' => $receiver,
            'receiver_cc' => [],
        ];
        try {
            trace("common task review push behavior" . request()->getUnionUserId(), 'DEBUG');
            Client::send('common_message_pushing', build_queue_data_with_xu($data));
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
        return;
    }
}
